package com.fangzhen.config;

import com.fangzhen.common.BaseResponse;
import com.fangzhen.exception.ServiceException;
import com.fangzhen.util.BaseResponseUtil;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 自定义全局异常处理器
 *
 * @author : z_sz
 * @date : 2020-09-09
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<String> handlerMethodArgumentNotValidException(
            MethodArgumentNotValidException methodArgumentNotValidException) {
        //创建字符串操作对象StringBuilder
        StringBuilder sb = new StringBuilder();
        // 获取所有校验问题,拼接返回
        List<FieldError> fieldErrors = methodArgumentNotValidException.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            sb.append(fieldError.getDefaultMessage()+",");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return BaseResponseUtil.fail(sb.toString());
    }
    /**
     * 业务异常处理
     * @param serviceException 自定义业务异常
     * @return 响应实体
     */
    @ExceptionHandler(ServiceException.class)
    public BaseResponse<String> handlerServiceException(ServiceException serviceException) {
        return BaseResponseUtil.fail(serviceException.getMessage());
    }

    /**
     * 系统异常处理
     * @param exception 系统异常
     * @return 响应实体
     */
    @ExceptionHandler(Exception.class)
    public BaseResponse<String> handlerSystemException(Exception exception) {
        return BaseResponseUtil.fail(exception.getMessage());
    }
}
